package com.hongpu.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hongpu.domain.HpProjectWorkPay;
import com.hongpu.service.HpProjectWorkPayService;
import com.hongpu.utils.ResultDto;
import com.hongpu.vo.HpProjectWorkPayExportExcelVo;
import com.hongpu.vo.HpProjectWorkPayVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 张玉胜
 * @since 2025年04月25日
 */
@RestController
@RequestMapping("/hpProjectWorkPay")
public class HpProjectWorkPayController {
    @Autowired
    HpProjectWorkPayService hpProjectWorkPayService;

    /**
     * 新增
     */
    @PostMapping("/add")
    public ResultDto add(@RequestBody HpProjectWorkPay hpProjectWorkPay){
        boolean save = hpProjectWorkPayService.add(hpProjectWorkPay);
        if(save){
            return ResultDto.ok();
        }
        return ResultDto.fail();
    }
    /**
     * 分页
     */
    @PostMapping("/page")
    public ResultDto page( @RequestBody HpProjectWorkPay hpProjectWorkPay){
        String projectName = hpProjectWorkPay.getProjectName();
        Page<?> page = new Page<>(hpProjectWorkPay.getCurrent(), hpProjectWorkPay.getSize());
        IPage<HpProjectWorkPayVo> selectPage = hpProjectWorkPayService.selectPage(page, projectName);
        return ResultDto.ok(selectPage);
    }

    /**
     * 根据项目ID删除项目
     */
    @PostMapping("/deleteById")
    public ResultDto deleteById(@RequestBody HpProjectWorkPay hpProjectWorkPay){
        try {
            QueryWrapper<HpProjectWorkPay> queryWrapper = new QueryWrapper<>(hpProjectWorkPay);
            List<HpProjectWorkPay> hpProjectWorkPays = hpProjectWorkPayService.getBaseMapper().selectList(queryWrapper);
            for (HpProjectWorkPay hpProjectWorkPay1 : hpProjectWorkPays) {
                Long id = hpProjectWorkPay1.getId();
               hpProjectWorkPayService.deleteById(id);
            }
            return ResultDto.ok();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导出
     */
    @GetMapping("/export/{projectName}")
    public void export(@PathVariable("projectName") String projectName, HttpServletResponse response) throws IOException {
        List<HpProjectWorkPayVo> list = hpProjectWorkPayService.selectList( projectName);
        List<HpProjectWorkPayExportExcelVo> data = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            HpProjectWorkPayVo hpProjectWorkPayVo = list.get(i);
            HpProjectWorkPayExportExcelVo vo = new HpProjectWorkPayExportExcelVo();
            vo.setXh(i + 1);
            vo.setProjectName(hpProjectWorkPayVo.getProjectName());
            vo.setInTotalContractAmount(hpProjectWorkPayVo.getInTotalContractAmount());
            vo.setInPaid(hpProjectWorkPayVo.getInPaid());
            vo.setInUnpaid(hpProjectWorkPayVo.getInUnpaid());
            vo.setOutTotalContractAmount(hpProjectWorkPayVo.getOutTotalContractAmount());
            vo.setSurplus(hpProjectWorkPayVo.getSurplus());
            data.add(vo);
        }

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");

            String fileName = URLEncoder.encode("收支管理报表"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), HpProjectWorkPayExportExcelVo.class).autoCloseStream(Boolean.FALSE).sheet("收支管理")
                    .doWrite(data);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            JSONObject failureMsg = new JSONObject();
            failureMsg.put("status", "failure");
            failureMsg.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(failureMsg.toString());
        }
    }
}